<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Tooltip Example</title>
    <style>
      .tooltip-trigger {
        position: relative;
        display: inline-block;
        cursor: pointer;
        padding: 10px 20px;
        background-color: #08c;
        color: white;
        border-radius: 4px;
      }

      .tooltip {
        position: absolute;
        left: 50%;
        transform: translateX(-50%);
        bottom: 100%;
        margin-bottom: 10px;
        padding: 5px 10px;
        background-color: #333;
        color: white;
        border-radius: 4px;
        white-space: nowrap;
        opacity: 0;
        visibility: hidden;
        transition: opacity 0.3s, visibility 0.3s;
        pointer-events: none;
        z-index: 10;
      }

      .tooltip-trigger:hover .tooltip {
        opacity: 1;
        visibility: visible;
      }
    </style>
  </head>
  <body>
    <div class="tooltip-trigger" id="trigger">
      Hover me
      <div class="tooltip" id="tooltip">This is a tooltip</div>
    </div>

    <script>
      document.addEventListener("DOMContentLoaded", () => {
        const trigger = document.getElementById("trigger");
        const tooltip = document.getElementById("tooltip");

        trigger.addEventListener("mouseenter", () => {
          const triggerRect = trigger.getBoundingClientRect();
          const tooltipRect = tooltip.getBoundingClientRect();
          const viewportWidth = window.innerWidth;
          const viewportHeight = window.innerHeight;

          let left =
            triggerRect.left + triggerRect.width / 2 - tooltipRect.width / 2;
          let top = triggerRect.bottom + 10;

          // Adjust left position if tooltip goes out of viewport
          if (left < 0) {
            left = 0;
          } else if (left + tooltipRect.width > viewportWidth) {
            left = viewportWidth - tooltipRect.width;
          }

          // Adjust top position if tooltip goes out of viewport
          if (top + tooltipRect.height > viewportHeight) {
            top = viewportHeight - tooltipRect.height - 10;
          }

          tooltip.style.left = `${left}px`;
          tooltip.style.top = `${top}px`;

          // Force reflow to update tooltip position before showing
          tooltip.offsetHeight;

          tooltip.style.opacity = 1;
          tooltip.style.visibility = "visible";
        });

        trigger.addEventListener("mouseleave", () => {
          tooltip.style.opacity = 0;
          tooltip.style.visibility = "hidden";
        });
      });
    </script>
  </body>
</html>
